package servlet.reader;

import com.alibaba.fastjson.JSONObject;
import entity.Borrow_books;
import entity.Pages;
import service.reader.Borrow_booksService;
import service.reader.impl.Borrow_booksServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Borrow_booksServlet
 *
 * @author lenovo
 * @since 2023/9/4
 */
@WebServlet("/borrow")
public class Borrow_booksServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    //引入服务层
    Borrow_booksService service = new Borrow_booksServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 接收参数
        String limit = req.getParameter("limit");
        String page = req.getParameter("page");
        String condition = (String) req.getParameter("condition");
        String conditionValue = (String) req.getParameter("conditionValue");
        if (page == null) {
            page = "1";
        }
        if (limit == null) {
            limit = "10";
        }
        // 准备返回参数
        int code = 1;
        String msg = "无数据";
        int count = 0;
        HttpSession session = req.getSession();
        //创建对象
        Pages<Borrow_books> pages = new Pages<>();
        pages.setPageSize(Integer.valueOf(limit));
        pages.setPageCountNo(Integer.valueOf(page));
        count = service.total(condition,conditionValue,session.getAttribute("reader"));
        pages.setPageCount(count);
        List<Borrow_books> list = service.getList(condition,conditionValue,session.getAttribute("reader"),pages);
        if (list != null){
            code = 0;
            msg = "有数据";
        }
        pages.setList(list);
        PrintWriter out = resp.getWriter();
        JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("msg",msg);
        json.put("count",count);
        json.put("data",pages.getList());
        out.print(json.toJSONString());
        System.out.println(json.toJSONString());
        out.flush();
        out.close();
    }
}
